package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsCategory;
import com.qf.service.CategoryService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @RequestMapping("/list")
    public Object list(Integer page,Integer limit,Integer id,String name,String sort,String order){
        IPage<DtsCategory> byPage = categoryService.findByPage(page, limit, id, name, sort, order);
        Map<String,Object> data = new HashMap<>();
        data.put("total",byPage.getTotal());
        data.put("items", byPage.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequestMapping("/l1")
    public Object l1(){
        List<DtsCategory> categories = categoryService.selectByPid();
        List<Map<String,Object>> data = new ArrayList<>();
        if (categories!= null){
            for (DtsCategory category : categories) {
                Map<String,Object> rootMenu = new HashMap<>();
                rootMenu.put("value", category.getId());
                rootMenu.put("label", category.getName());
                data.add(rootMenu);
            }
        }

        return ResponseUtil.ok(data);
    }

    @RequestMapping("/create")
    public Object create(@RequestBody DtsCategory category){
        int add = categoryService.add(category);
        if (add == 0){
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok(category);
    }

    @RequestMapping("/update")
    public Object update(@RequestBody  DtsCategory category){
        int update = categoryService.update(category);
        if (update == 0){
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(category);
    }

    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsCategory category){
        categoryService.deleteById(category);
        return ResponseUtil.ok();
    }
}
